<?php
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modeladmin');
class RaovatModelRaovat extends JModelAdmin{
	protected function allowEdit($data = array(), $key = 'id'){

		return JFactory::getUser()->authorise('core.edit', 'com_raovat.message.'.((int) isset($data[$key]) ? $data[$key] : 0)) or parent::allowEdit($data, $key);
	}
	public function getTable($type = 'raovat', $prefix = 'RaovatTable', $config = array()) 
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	
	public function getForm($data = array(), $loadData = true) 
	{
		
		$form = $this->loadForm('com_raovat.raovat', 'raovat', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) 
		{
			return false;
		}
		return $form;
	}
	
	public function getScript() 
	{
		return 'administrator/components/com_raovat/models/forms/raovat.js';
	}
	
	protected function prepareTable($table)
	{
		if (!$table->id)
		{
			$table->registe_date = date('Y-m-d');
		}
		
		if ($_FILES['jform']['name']['image']){
			jimport('joomla.filesystem.file');
			$filename = JFile::makeSafe($_FILES['jform']['name']['image']);
			$filename = date('Ymdhis').rand(0,10).'_'.strtolower(str_replace(" ","_", $filename));
			$src = $_FILES['jform']['tmp_name']['image'];
			$dest = JPATH_ROOT."/"."images"."/".$filename;
			if (strtolower(JFile::getExt($filename) ) == 'jpg' || 
				strtolower(JFile::getExt($filename) ) == 'png' ||
				strtolower(JFile::getExt($filename) ) == 'gif'){
			   if ( JFile::upload($src, $dest) ) {
			      $table->image = $filename;
			      if ($table->id){
			   		$db = &JFactory::getDbo();
					$query = $db->getQuery(true);
					$query->select('*');
					$query->from('#__raovat');
					$query->where('id='.$table->id);
					$db->setQuery((string)$query);
					$old_img = $db->loadObject();
					if ($old_img->image && JFile::exists(JPATH_ROOT."/"."images"."/".$old_img->image)){
						JFile::delete(JPATH_ROOT."/"."images"."/".$old_img->image);
					}
			      }
			   } 
			} 
		}
		
	}
	protected function loadFormData() 
	{
		
		$data = JFactory::getApplication()->getUserState('com_raovat.edit.raovat.data', array());
		if (empty($data)) 
		{
			$data = $this->getItem();
		}
		return $data;
	}
	public function getItem($pk = null)
	{
		$item = parent::getItem($pk);
		
		
		return $item;
	}
	
}
